/*
*/

#include "rtc.h"

#include "display.h"


void InitRTC(void){
    if(BKP_ReadBackupRegister(BKP_DR1) != 0x5A5A){
	/* Backup data register value is not correct or not yet programmed 
	(when the first time the program is executed) */
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR|RCC_APB1Periph_BKP, ENABLE);
	//Enable PWR and BKP clocks
	PWR_BackupAccessCmd(ENABLE);
	BKP_DeInit();	//Reset Backup Domain
	RCC_LSEConfig(RCC_LSE_ON);
	while(RCC_GetFlagStatus(RCC_FLAG_LSERDY)==RESET)
	    __WFI(); 	//Wait till LSE is ready
	RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);//Select LSE as RTC Clock Source
	RCC_RTCCLKCmd(ENABLE);
	RTC_SetPrescaler(32767);
	//* RTC period = RTCCLK/RTC_PR = (32.768 KHz)/(32767+1)
	BKP_WriteBackupRegister(BKP_DR1, 0x5A5A);
    }
    RTC_WaitForSynchro();
    //Wait for RTC registers synchronization
    //RTC_ITConfig(RTC_IT_SEC, ENABLE);	//Enable the RTC Second
    RTC_WaitForLastTask();
    //Wait until last write operation on RTC registers has finished
}

void TestRTC(void){
    DisplayDec(RTC_GetCounter()%1000,0);
}